package login

import (
	session2 "OnlineRetailers/controllers/admin/session"
	"OnlineRetailers/controllers/errorDeal"
	"OnlineRetailers/models"
	"OnlineRetailers/models/Admin"
	USER "OnlineRetailers/models/User"
	"OnlineRetailers/models/User/resMes"
	error2 "OnlineRetailers/models/errorDeal"
	"encoding/json"
	"fmt"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	"io/ioutil"
	"net/http"
)

type WXLogin struct {
	beego.Controller
}

func getOpenId(code string) (err error, res *resMes.GetOpenId) {

	o := orm.NewOrm()

	//fmt.Println(code)

	client := &http.Client{}

	url := models.GetOpenIdUrl + "?appid=" + models.AppId + "&secret=" + models.Secret + "&js_code=" + code + "&grant_type=" + models.Grant
	//fmt.Println(url)

	resp, err := client.Get(url)

	if err != nil {
		return
	}

	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)

	if err != nil {
		return
	}
	err = json.Unmarshal(body, &res)

	if err != nil {
		return
	}

	if res.ErrCode == 0 {
		if o.QueryTable("w_x_user").Filter("openId__exact", res.OpenId).Exist() {
			user := &USER.WXUser{OpenId: res.OpenId}
			err = o.Read(user, "openId")
			if err != nil {
				return
			}
			res.User = user
		}
	} else {
		err = fmt.Errorf(res.ErrMsg, res.ErrCode)
	}

	return nil, res
}

func (c *WXLogin) WXLogin() {

	defer c.ServeJSON()

	res := &resMes.GetUser{}
	openId := &resMes.GetOpenId{}
	o := orm.NewOrm()
	user := USER.WXUser{}
	code := c.GetString("code")
	user.Name = c.GetString("name")
	user.Picture = c.GetString("picture")
	log := &error2.Log{}
	mes := &error2.Mes{}

	var err error
	var addr = "/login/WXLogin"

	err, openId = getOpenId(code)
	if err != nil {
		c.Data["json"] = errorDeal.ErrMess(log, "400", err, addr, err.Error())
		return
	}

	exi := o.QueryTable("w_x_user").Filter("openId__exact", openId.OpenId).Exist()
	if !exi && user.Name == "" && user.Picture == "" {
		c.Data["json"] = errorDeal.ErrLightMess(mes, "401", "未注册")
		return
	} else if !exi {
		user.OpenId = openId.OpenId
		user.Address = &USER.Address{AddressId: "0"}
		_, err := o.Insert(&user)
		if err != nil {
			c.Data["json"] = errorDeal.ErrMess(log, "400", err, addr, err.Error())
			return
		}
	} else {
		sql := "select * from `w_x_user` where open_id=?"
		err = o.Raw(sql, openId.OpenId).QueryRow(&user)
		if err != nil {
			c.Data["json"] = errorDeal.ErrMess(log, "400", err, addr, err.Error())
			return
		}
	}

	if err = session2.NewSession(&Admin.Session{SessionId: openId.OpenId}, []byte(openId.OpenId)); err != nil {
		c.Data["json"] = errorDeal.ErrMess(log, "400", err, addr, err.Error())
		return
	}
	res.User = &user
	res.Code = "200"
	c.Data["json"] = res
}
